package com.lgx.mall.core.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.service.IIntraCityService;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.mall.core.entity.Product;
import com.lgx.mall.core.service.IBrandService;
import com.lgx.mall.core.service.ICategoryService;
import com.lgx.mall.core.service.IProductService;

@Controller
@RequestMapping("/product")
public class ProductController {

	@Autowired
	private IProductService productService;

	public IProductService getProductService() {
		return productService;
	}

	public void setProductService(IProductService productService) {
		this.productService = productService;
	}
	
	@Autowired
	private IIntraCityService intraCityService;

	public IIntraCityService getIntraCityService() {
		return intraCityService;
	}

	public void setIntraCityService(IIntraCityService intraCityService) {
		this.intraCityService = intraCityService;
	}
	
	@Autowired
	private IBrandService brandService;

	public IBrandService getBrandService() {
		return brandService;
	}

	public void setBrandService(IBrandService brandService) {
		this.brandService = brandService;
	}
	
	@Autowired
	private ICategoryService categoryService;

	public ICategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(ICategoryService categoryService) {
		this.categoryService = categoryService;
	}

	@RequestMapping("/productMgr.do")
	public String productMgr(HttpServletRequest request,HttpServletResponse response)
	{
		//商品分区类型
		List<Dictionary> areaCategory = DictUtils.getDictListByKind(DictUtils.PRODUCT_AREA);
		request.setAttribute("areaCategory", areaCategory);
		
		return "mall/core/product/productMgr";
	}
	
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response)
	{
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		Object[] params = new Object[10];
		String name = request.getParameter("name");
		String code = request.getParameter("code");
		String areaCategory = request.getParameter("areaCategory");
		String category = request.getParameter("category");
		params[0] = areaCategory;
		if(!StringUtils.isEmpty(category) && !category.equals("所有")){
			params[1] = category;
		}else{
			params[1] = "";
		}
		if(!StringUtils.isEmpty(name))
		{
			params[2] = name;
		}else{
			params[2] = "";
		}
		if(!StringUtils.isEmpty(code))
		{
			params[3] = code;
		}else{
			params[3] = "";
		}
		
		Pagination page = this.productService.findProductPagination(params, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
		Json2Utils.parseJSON(page, response);
	}
	
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response)
	{
		String type = request.getParameter("type");
		if(type.equals("edit")){
			String productId = request.getParameter("productId");
			request.setAttribute("productId", productId);
			Product product = this.productService.findProductById(Long.parseLong(productId));
			request.setAttribute("product", product);
		}else{

			//配送说明
			String farewaydesc = " <p> "+
					" 	&nbsp;</p> "+
					" <p> "+
					" 	国内运输方式及费用情况</p> "+
					" <p> "+
					" 	运输方式：全国各地的协议快递、EMS及物流运输。</p> "+
					" <p> "+
					" 	<strong>一、快递公司</strong></p> "+
					" <p> "+
					" 	1、 快递(顺丰速运：<a href=\"http://www.sf-express.com/\">www.sf-express.com</a>)</p> "+
					" <p> "+
					" 	(1)本省省内12元/KG,超出按6-8元/KG收取,正常情况下1-2天到货.</p> "+
					" <p> "+
					" 	(2)外围地区快递费一般为20元/KG首重,超出按8-15元/KG收取,正常情况下2-5天到货.</p> "+
					" <p> "+
					" 	2、 快递(圆通快递：<a href=\"http://www.yto.net.cn/\">http://www.yto.net.cn</a>)</p> "+
					" <p> "+
					" 	(1)本省省内8元/KG,超出按2-6元/KG收取,正常情况下1-2天到货.</p> "+
					" <p> "+
					" 	(2)外围地区快递费一般为10-15元/KG首重,超出按8-15元/KG收取,正常情况下2-5天到货.</p> "+
					" <p> "+
					" 	3、 快递(韵达快递： <a href=\"http://www.yundaex.com/\">http://www.yundaex.com</a>)</p> "+
					" <p> "+
					" 	(1)本省省内10元/KG,超出按5元/KG收取,正常情况下1-2天到货.</p> "+
					" <p> "+
					" 	(2)外围地区快递费一般为12元/KG首重,超出按8-15元/KG收取,正常情况下2-5天到货.</p> "+
					" <p> "+
					" 	4、 快递(天天快递：<a href=\"http://www.ttkdex.com/\">http://www.ttkdex.com</a>)</p> "+
					" <p> "+
					" 	(1)本省省内10元/KG,超出按5元/KG收取,正常情况下1-2天到货.</p> "+
					" <p> "+
					" 	(2)外围地区快递费一般为15元/KG首重,超出按8-15元/KG收取,正常情况下2-5天到货.</p> "+
					" <p> "+
					" 	<strong>二、邮政及</strong><strong>EMS</strong><strong>快递（快递无法抵达的地区可选用</strong><strong>EMS</strong><strong>或者邮寄）</strong></p> "+
					" <p> "+
					" 	EMS快递：全国各地均可到达，首重21元/公斤(含1元面单费)，续重按不同地区加收6-15元/公斤，费用较高，不建议使用</p> "+
					" <p> "+
					" 	<strong>三、物流运输：（需到物流点自提）。</strong></p> "+
					" <p> "+
					" 	(1)30元/15公斤内，续重1公斤/1-3元，4-7天可达；保价费按千分之一收取</p> "+
					" <p> "+
					" 	(2)部分城市部分地区不能送达。如需送货上门，需事先查询是否可送货上门，送货上门价格自行与物流公司商议</p> "+
					" <p> "+
					" 	四、汽车运输：建议15公斤以上使用，需到车站自取</p> "+
					" <p> "+
					" 	(1)35-40元/15公斤内，续重1公斤/2-6元，2-5天可达，保价费按千分之一收取</p> "+
					" <p> "+
					" 	(2)要求有到达目的地的专线车，需事先咨询或提供专线车地点。</p> "+
					" <p> "+
					" 	五、其它快递：协议快递除外的快递，比如申通快递等快递客户可以指定使用这些快递，但是费用通常比协议快递收费要更高一些，按其实际的收取标准。</p> "+
					" <p> "+
					" 	<strong>六、同城快递</strong></p> "+
					" <p> "+
					" 	1、购买共享同城产品或长沙站产品，凭手机短信可直接到指定地点提货。</p> "+
					" <p> "+
					" 	2、需要送货上门需支付同城快递费用每件8元。大件、特大件商品协商价格。</p> "+
					" <p> "+
					" 	<strong>备注：</strong></p> "+
					" <p> "+
					" 	1.请自行确认当地是否有顺丰，圆通，韵达，天天网点</p> "+
					" <p> "+
					" 	2.运费到付收费一般略贵于现付的运费，到付具体费用以实际收费为准</p> "+
					" <p> "+
					" 	3.节假日的运输根据各运输公司的不同情况而确定，可能会公布顺延，有可能在节假日照常发货，请您在节假日期间购买商品时注意其发货通知，发货情况可即时咨询</p> "+
					" <p> "+
					" 	4.正常情况下省会城市1-2天到货，二级城市2-3天到货，三级城市2-5天到货。</p> ";
			
			request.setAttribute("farewaydesc", farewaydesc);
			
			//售后服务
			String saledesc = " <p> "+
					" 	欢迎您来到乐共享商城，为了保障您在乐共享增值服务平台兑换商品的权益，请抽出您几分钟宝贵时间，阅读以下条款，谢谢！<br /> "+
					" 	请您尽量使用支付宝，网银付款。<br /> "+
					" 	如需使用其它支付方式，请先联系在线客服。<br /> "+
					" 	兑换确认<br /> "+
					" 	1. 由于电子商务的特点，商品图片可能会出现由于光线或显示器等原因，使实物颜色与照片有些差别，这属于正常现象，请于下单前仔细检查您所需要的商品颜色、款式、尺寸等信息，以避免引起不必要的误会。<br /> "+
					" 	2. 如果需要帮助，请咨询在线客服或400-8866-756与我们联系，我们的专职客服竭诚为您服务。<br /> "+
					" 	发货规则<br /> "+
					" 	1. 本商城货物运费在兑换时一起支付（特别说明情况下除外），在您提交订单时本商城将列出不同的发货方式供您选择，我们会委托您指定的货运公司或快递公司按您的要求及时发货给您,收货时请留意货物外包装有无损坏或异样，建议您在收货时当场清点货物，货物如有破损或遗失，应及时向货运公司索赔。<br /> "+
					" 	2. 每天中午12点安排发货，超过12点的订单于次日12点安排，节假日暂停发货，在此期间的订单将于节假日后的第一个工作日安排发货；由于商品一般由厂家等供应商发货，不同供应商商品运费分别计算；<br /> "+
					" 	3. 特别说明：因发货都是通过物流快递等，打包带来的细微折痕是难以避免的，如遇到这种情况，请多多包涵。</p> "+
					" <p> "+
					" 	货到验收<br /> "+
					" 	1.在收到包裹的时候，请先查看外包装是否完整，并当着送件员面打开检查是否有损坏、物品和数量是否正确，如出现问题，为保障您的权益，请拒绝在快递单签字，拒收，在送件员在场的情况下，及时联系乐共享客服人员反映情况；<br /> "+
					" 	2.未经检验就在快递单上签字，证明您已确认货物完好，数量正确，凡在确认收货24小时后再提出的货品破损或遗失问题我们不予负责，责任将由您个人承担。<br /> "+
					" 	3.收到包裹后有任何其他问题请及时联系我们，我们会尽快为您解决任何问题。</p> "+
					" <p> "+
					" 	订单兑换规定<br /> "+
					" 	1.乐共享商城兑换订单不支持退单；<br /> "+
					" 	2.非质量问题，乐共享商城不支持退换货服务；<br /> "+
					" 	3.质量问题由乐共享商城对该类商品承担退换货服务，需收货人在签收后24小时内提出，并及时联系乐共享客服人员并提供照片.过期概不负责。此种情况因会员已签收，退换货运费由会员承担；退回时需保证物件齐全；<br /> "+
					" 	4.商品无质量问题，不签收、不取件的一切责任由会员本人承担，乐共享有权根据订单交易成功处理，兑换时支付的积分和运费不退还。</p> "+
					" <p> "+
					" 	注意<br /> "+
					" 	1.退货时请避免使用不可查询的邮寄手段，如果因此而发生商品遗失、破损、误送等情况，乐共享不承担责任，敬请谅解!以实际收货地址确定运费。<br /> "+
					" 	2.退回瑕疵商品前请先与客服确认同意 。<br /> "+
					" 	3.签收后以下情况的退回商品，一律视为丢弃.不予退款：<br /> "+
					" 	（A）未征得本站正式同意直接退回的商品；<br /> "+
					" 	（B）征得本站正式同意但逾期退回之商品（以退货发出日期为准）；<br /> "+
					" 	（C）征得本站同意但退回的商品包装不完整，有损坏等不符合退换货要求的；</p> "+
					" <p> "+
					" 	温馨提示：亲爱的会员们请注意，为充分保障您的权益，请在您签收包裹前仔细检查包裹外包装是否完好，特别是胶带粘贴范围、包裹侧面以及包裹背面，若有任何异常现象请暂时不要签收包裹，及时联系乐共享商城，我们的工作人员会予以处理。若您签收下包裹，责任方将由配送公司过度到贵方，事后若发现包裹有破损并且缺失商品等情况时，快递公司将不予承担任何责任，为此请朋友们签收包裹前一定要仔细检查！以免承担不必要的损失！</p> "+
					" <p> "+
					" 	服务热线：400-8866-756<br /> "+
					" 	服务时间：9:00-20:00 (周一至周五) 9:00-17:30 (周六至周日)</p> ";
			
			request.setAttribute("saledesc", saledesc);
		}
		
		//商品分区类型
		List<Dictionary> areaCategory = DictUtils.getDictListByKind(DictUtils.PRODUCT_AREA);
		request.setAttribute("areaCategory", areaCategory);
		
		//是否上架
		List<Dictionary> onsale = DictUtils.getDictListByKind(DictUtils.PRODUCT_ONSALE);
		request.setAttribute("onsale", onsale);
		
		//可选颜色
		List<Dictionary> color = DictUtils.getDictListByKind(DictUtils.PRODUCT_COLOR);
		request.setAttribute("color", color);
		
		//可选衣服尺码
		List<Dictionary> clothessize = DictUtils.getDictListByKind(DictUtils.PRODUCT_CLOTHESSIZE);
		request.setAttribute("clothessize", clothessize);
		
		//可选鞋子尺码
		List<Dictionary> shoesize = DictUtils.getDictListByKind(DictUtils.PRODUCT_SHOESIZE);
		request.setAttribute("shoesize", shoesize);
		
		//可选运费支付方式
		List<Dictionary> fareway = DictUtils.getDictListByKind(DictUtils.PRODUCT_FAREWAY);
		request.setAttribute("fareway", fareway);
		
		request.setAttribute("type", type);
		
		
		return "mall/core/product/product-init";
	}
	
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response)
	{
		String name = request.getParameter("name");
		if(!StringUtils.isEmpty(name))name = EscapeUtils.unescape(name);
		String areaNode = request.getParameter("areaNode");
		if(!StringUtils.isEmpty(areaNode))areaNode = EscapeUtils.unescape(areaNode);
		String code = request.getParameter("code");
		if(!StringUtils.isEmpty(code))code = EscapeUtils.unescape(code);
		String imageUrl = request.getParameter("imageUrl");
		if(!StringUtils.isEmpty(imageUrl))imageUrl = EscapeUtils.unescape(imageUrl);
		String price = request.getParameter("price");
		if(!StringUtils.isEmpty(price))price = EscapeUtils.unescape(price);
		String leaves = request.getParameter("leaves");
		if(!StringUtils.isEmpty(leaves))leaves = EscapeUtils.unescape(leaves);
		String brand = request.getParameter("brand");
		if(!StringUtils.isEmpty(brand))brand = EscapeUtils.unescape(brand);
		String onsale = request.getParameter("onsale");
		if(!StringUtils.isEmpty(onsale))onsale = EscapeUtils.unescape(onsale);
		String areaCategory = request.getParameter("areaCategory");
		if(!StringUtils.isEmpty(areaCategory))areaCategory = EscapeUtils.unescape(areaCategory);
		String category = request.getParameter("category");
		if(!StringUtils.isEmpty(category))category = EscapeUtils.unescape(category);
		String color = request.getParameter("color");
		if(!StringUtils.isEmpty(color))color = EscapeUtils.unescape(color);
		String clothessize = request.getParameter("clothessize");
		if(!StringUtils.isEmpty(clothessize))clothessize = EscapeUtils.unescape(clothessize);
		String shoesize = request.getParameter("shoesize");
		if(!StringUtils.isEmpty(shoesize))shoesize = EscapeUtils.unescape(shoesize);
		String weight = request.getParameter("weight");
		if(!StringUtils.isEmpty(weight))weight = EscapeUtils.unescape(weight);
		String fareway = request.getParameter("fareway");
		if(!StringUtils.isEmpty(fareway))fareway = EscapeUtils.unescape(fareway);
		String description = request.getParameter("description");
		if(!StringUtils.isEmpty(description))description = EscapeUtils.unescape(description);
		String farewaydesc = request.getParameter("farewaydesc");
		if(!StringUtils.isEmpty(farewaydesc))farewaydesc = EscapeUtils.unescape(farewaydesc);
		String saledesc = request.getParameter("saledesc");
		if(!StringUtils.isEmpty(saledesc))saledesc = EscapeUtils.unescape(saledesc);
		
		Product p = new Product();
		p.setName(name);
		p.setAreaNode(areaNode);
		p.setCode(code);
		p.setImageUrl1(imageUrl);
		p.setPrice(Double.parseDouble(price));
		p.setLeaves(Integer.parseInt(leaves));
		p.setBrand(this.brandService.findBrandById(Integer.parseInt(brand)));
		p.setOnsale(Integer.parseInt(onsale));
		p.setAreaCategory(Integer.parseInt(areaCategory));
		p.setCategory(this.categoryService.findCategoryById(Integer.parseInt(category)));
		p.setColor(color);
		p.setClothessize(clothessize);
		p.setShoesize(shoesize);
		if(!weight.isEmpty()){
			p.setWeight(Double.parseDouble(weight));
		}
		p.setFareway(farewaydesc);
		p.setDescription(description);
		p.setFarewaydesc(farewaydesc);
		p.setSaledesc(saledesc);
		
		try {
			this.productService.createProduct(p);
		} catch (DataException e1) {
			e1.printStackTrace();
		}
		
		request.setAttribute("message", "操作成功！");
		return "1";
	}
	
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException
	{
		String productId = request.getParameter("productId");
		Product p = this.productService.findProductById(Long.parseLong(productId));
		
		String name = request.getParameter("name");
		if(!StringUtils.isEmpty(name))name = EscapeUtils.unescape(name);
		String areaNode = request.getParameter("areaNode");
		if(!StringUtils.isEmpty(areaNode))areaNode = EscapeUtils.unescape(areaNode);
		String code = request.getParameter("code");
		if(!StringUtils.isEmpty(code))code = EscapeUtils.unescape(code);
		String imageUrl = request.getParameter("imageUrl");
		if(!StringUtils.isEmpty(imageUrl))imageUrl = EscapeUtils.unescape(imageUrl);
		String price = request.getParameter("price");
		if(!StringUtils.isEmpty(price))price = EscapeUtils.unescape(price);
		String leaves = request.getParameter("leaves");
		if(!StringUtils.isEmpty(leaves))leaves = EscapeUtils.unescape(leaves);
		String brand = request.getParameter("brand");
		if(!StringUtils.isEmpty(brand))brand = EscapeUtils.unescape(brand);
		String onsale = request.getParameter("onsale");
		if(!StringUtils.isEmpty(onsale))onsale = EscapeUtils.unescape(onsale);
		String areaCategory = request.getParameter("areaCategory");
		if(!StringUtils.isEmpty(areaCategory))areaCategory = EscapeUtils.unescape(areaCategory);
		String category = request.getParameter("category");
		if(!StringUtils.isEmpty(category))category = EscapeUtils.unescape(category);
		String color = request.getParameter("color");
		if(!StringUtils.isEmpty(color))color = EscapeUtils.unescape(color);
		String clothessize = request.getParameter("clothessize");
		if(!StringUtils.isEmpty(clothessize))clothessize = EscapeUtils.unescape(clothessize);
		String shoesize = request.getParameter("shoesize");
		if(!StringUtils.isEmpty(shoesize))shoesize = EscapeUtils.unescape(shoesize);
		String weight = request.getParameter("weight");
		if(!StringUtils.isEmpty(weight))weight = EscapeUtils.unescape(weight);
		String fareway = request.getParameter("fareway");
		if(!StringUtils.isEmpty(fareway))fareway = EscapeUtils.unescape(fareway);
		String description = request.getParameter("description");
		if(!StringUtils.isEmpty(description))description = EscapeUtils.unescape(description);
		String farewaydesc = request.getParameter("farewaydesc");
		if(!StringUtils.isEmpty(farewaydesc))farewaydesc = EscapeUtils.unescape(farewaydesc);
		String saledesc = request.getParameter("saledesc");
		if(!StringUtils.isEmpty(saledesc))saledesc = EscapeUtils.unescape(saledesc);
		
		p.setName(name);
		p.setAreaNode(areaNode);
		p.setCode(code);
		p.setImageUrl1(imageUrl);
		p.setPrice(Double.parseDouble(price));
		p.setLeaves(Integer.parseInt(leaves));
		p.setBrand(this.brandService.findBrandById(Integer.parseInt(brand)));
		p.setOnsale(Integer.parseInt(onsale));
		p.setAreaCategory(Integer.parseInt(areaCategory));
		p.setCategory(this.categoryService.findCategoryById(Integer.parseInt(category)));
		p.setColor(color);
		p.setClothessize(clothessize);
		p.setShoesize(shoesize);
		if(!weight.isEmpty()){
			p.setWeight(Double.parseDouble(weight));
		}
		p.setFareway(farewaydesc);
		p.setDescription(description);
		p.setFarewaydesc(farewaydesc);
		p.setSaledesc(saledesc);
		
		try {
			this.productService.updateProduct(p);
		} catch (DataException e1) {
			e1.printStackTrace();
		}
		
		request.setAttribute("message", "操作成功！");
		return "1";
	}
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response)
	{
//		String productId = request.getParameter("productId");
//		try {
//			this.productService.deleteProduct(Long.parseLong(productId));
//			return "1";
//		} catch (DataException e1) {
//			e1.printStackTrace();
//		}
//		return "0";
		
		String ids = request.getParameter("ids");
		try {
			this.productService.deleteProducts(ids.split(","));
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
}
